<?php
/**
 * Created by PhpStorm.
 * User: kevin
 * Date: 15-6-15
 * Time: 下午6:01
 */

/*
 * 判断用户是否登录过
 */
function is_login(){
    $user = session('user_auth');
    if(empty($user)){
        return 0;
    }else{
        return $user['uid'];
    }
}

/*
 * 检测用户是否是管理员
 */
function is_admin($uid = null){
    $uid = is_null($uid)?is_login():$uid;
    return $uid && (intval($uid) === C('USER_ADMINISTRATOR'));
}

//检测是否是管理员
function is_administrator($uid = null){
    $uid = is_null($uid) ? is_login() : $uid;
    return $uid && (intval($uid) === C('USER_ADMINISTRATOR'));
}

/*
 * 把返回的数据集转换成Tree
 */
function list_to_tree($list, $pk='id', $pid = 'pid', $child = '_child', $root = 0) {
    // 创建Tree
    $tree = array();
    if(is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] =& $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId =  $data[$pid];
            if ($root == $parentId) {
                $tree[] =& $list[$key];
            }else{
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}
/*
    * 检查用户IP
    */
function checkip(){
    $ip = get_client_ip();
    $map['ip'] = array('LIKE',"%".$ip."%");
    $uid = M('Taskip')->where($map)->getField('uid');
    if($uid){
        return $uid;
    }else{
        return false;
    }
}
/*
 * 根据department获取用户名
 */
function getusername($uid){
    $User = new User\Api\UserApi();
    $info = $User->info($uid);
    if($info && isset($info['1'])){
        $name = $info[1];
    }else{
        $name ='';
    }
    return $name;
}

/*
 * 获取科技查新统计信息
 */
function taskCount($array){
    $data['allCount'] = M('Task')->where($array)->count();
    $data['newCount'] = M('Task')->where($array)->where('status=1')->count();
    $data['completeCount'] = M('Task')->where($array)->where('status=2')->count();
    $data['processingCount'] = M('Task')->where($array)->where('status=3')->count();
    return $data;
}

/*
 *获取用户统计信息
 */

function userCount($department){
    $userCount = M('User')->where($department)->count();
    return $userCount;
}

/**
 * 系统邮件发送函数
 * @param string $to    接收邮件者邮箱
 * @param string $name  接收邮件者名称
 * @param string $subject 邮件主题
 * @param string $body    邮件内容
 * @param string $attachment 附件列表
 * @return boolean
 */
function think_send_mail($to, $name, $subject = '', $body = '', $attachment = null){
    $config = C('THINK_EMAIL');
    vendor('PHPMailer.class#phpmailer'); //从PHPMailer目录导class.phpmailer.php类文件
    $mail             = new PHPMailer(); //PHPMailer对象
    $mail->CharSet    = 'UTF-8'; //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
    $mail->ISSMTP();  // 设定使用SMTP服务
    $mail->SMTPDebug  = 0;                     // 关闭SMTP调试功能
    // 1 = errors and messages
    // 2 = messages only
    $mail->SMTPAuth   = true;                  // 启用 SMTP 验证功能
//    $mail->SMTPSecure = '';                 // 使用安全协议
    $mail->Host       = $config['SMTP_HOST'];  // SMTP 服务器
    $mail->Port       = $config['SMTP_PORT'];  // SMTP服务器的端口号
    $mail->Username   = $config['SMTP_USER'];  // SMTP服务器用户名
    $mail->Password   = $config['SMTP_PASS'];  // SMTP服务器密码
    $mail->SetFrom($config['FROM_EMAIL'], $config['FROM_NAME']);
    $replyEmail       = $config['REPLY_EMAIL']?$config['REPLY_EMAIL']:$config['FROM_EMAIL'];
    $replyName        = $config['REPLY_NAME']?$config['REPLY_NAME']:$config['FROM_NAME'];

    $mail->AddReplyTo($replyEmail, $replyName);
    $mail->Subject    = $subject;
    $mail->MsgHTML($body);
    $mail->AddAddress($to, $name);
    if(is_array($attachment)){ // 添加附件
        foreach ($attachment as $file){
            is_file($file) && $mail->AddAttachment($file);
        }
    }
    return $mail->Send() ? true : $mail->ErrorInfo;
}

function getCitySelect(){
    $city = M('Area')->where('pid=0')->getField('area_id,title');
    return $city;
}

function getAllCity(){
    $city = M('Area')->where('pid=0')->select();
    return $city;
}

function getCategorySelect(){
    $category = M('Category')->where('pid=0')->getField('category_id,title');
    return $category;
}

function getAllCategroy(){
    $category = M('Category')->where('pid=1')->select();
    return $category;
}

/**
 * 获取省市
 * @return array
 */
function getProvince(){
    $cityList = array();
    $cityModel          = M('area');
    $departmentModel    = M('department');
    $departmentList     = $departmentModel->group('city')->select();
    foreach($departmentList as $k=>$v){
        $cityList[$k]['area_id'] = $v['city'];
        $cityInfo = $cityModel->where('title="江苏省"')->where(array('area_id'=>$v['city']))->find();
        $cityList[$k]['title'] = $cityInfo['title'];
    }
    return $cityList;
}

/**
 * 获取学校学科类型
 * @return array|mixed
 */
function getSchoolType(){
    $schoolTypeList     = array();
    $schoolTypeModel    = M('school_type');
    $schoolTypeList     = $schoolTypeModel->select();
    return $schoolTypeList;
}

/**
 * 根据学科id获取学科标题
 * @param int $id
 * @return mixed
 */
function getSchooTypeById($id=0){
    return M('school_type')->where(array('id'=>$id))->getField('title');
}
/**
 * 获取开通账户的机构
 * @return array|mixed
 */
function getUnitList(){
    $unitList           = array();
    $departmentModel    = M('department');
    $unitList           = $departmentModel->select();
    return $unitList;
}
//获取机构
function getJg(){
   return M('cxjg')->select();
}
//获取机构类型
function getTypeSelect(){
    $type = array(
        '1'=>'自助',
        '2'=>'挂靠'
    );
        return $type;
}
//根据机构类型ID返回类型
function getTitleByType($id){
    switch($id){
        case '1':
            return "自助";
        case '2':
            return "挂靠";
    }
}

function getUserStatus($status){
    switch($status){
        case '0':
            return "禁用";
        case '1':
            return "正常";
        case '-1':
            return "用户组删除";
    }
}
//格式化字节大小  数据库备份中使用
function format_bytes($size, $delimiter = '') {
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}

//调用API接口
function api($name,$vars=array()){
    $array     = explode('/',$name);
    $method    = array_pop($array);
    $classname = array_pop($array);
    $module    = $array? array_pop($array) : 'Common';
    $callback  = $module.'\\Api\\'.$classname.'Api::'.$method;
    if(is_string($vars)) {
        parse_str($vars,$vars);
    }
    return call_user_func_array($callback,$vars);
}

/*
 * 获取学院类型
 */
function getSchoolTypeSelect(){
    $res = M('SchoolType')->order('id desc')->getField('id,title');
    return $res;
}

/*
 * 获取项目级别
 */
function getLevelRadio(){
    $level = array(
        '1'=>'国家级',
        '2'=>'省部级',
        '3'=>'市级',
        '4'=>'其他'
    );
    return $level;
}

/*
 * 获取付款方式
 */
function getPaymentRadio(){
    $res = M('Payment')->getField('id,title');
    return $res;
}

/*
 * 获取报告方式
 */
function getReportRadio(){
    $method = array(
        '1'=>'自取',
        '2'=>'快递'
    );
    return $method;
}

//获取查新目的
function getCxmdCheckbox(){
    $cxmd = array(
        '1'=>' 科研立项 ',
        '2'=>'鉴定、验收、评价',
        '3'=>' 奖励申报 ',
        '4'=>' 申请专利 ',
        '5'=>' 博硕士论文开题 ',
        '6'=>' 其他',
		'7'=>'申报高新技术企业',
		'8'=>'申报高新技术产品'
    );
    return $cxmd;
}
//获取查新要求

function getCxyqCheckbox(){
    $cxyq = array(
        '1'=>' 希望查新机构通过查新，证明在所查范围内国内外有无相同或类似研究 ',
        '2'=>'希望查新机构对查新项目分别或综合进行国内外对比分析',
        '3'=>' 查新委托人提出的其他愿望 ',
    );
    return $cxyq;
}
//获取查新区域
function getArea(){
    $area = array(
        '1'=>' 国内查新 ',
        '2'=>' 国外查新 ',
        '3'=>' 国内外查新'
    );
    return $area;
}

//获取用户来源
function getUserSource(){
    $UserSource = array(
        '1'=>'校内',
        '2'=>'校外'
    );
    return $UserSource;
}

//根据taskId获取项目名称
function getNameByTaskId($str){
    $id = (int)$str;
    $map['id'] = $id;
    $name = M('Kjcx')->where($map)->getField('xmmc');
    return $name;
}

//附件转换成连接
function get_Flie_links($str){
	$sqfj_arr=explode(',',$str);
	$file_link='';
	foreach($sqfj_arr as $key => $value){
		if($value != ''){
			$file_link.='<a target="_blank" href="./ajax_control/?action=down_file&file_id='.$value.'"><img src="'.__ROOT__.'/Public/img/downpic.gif" style="padding:0 3px;"></a>';
		}
	}
	return $file_link;
}

function get_File_links($str){
    $sqfj_arr=explode(',',$str);
    $file_link='';
    foreach($sqfj_arr as $key => $value){
        if($value != ''){
            $file_link.='<a target="_blank" href="./down_file/?file_id='.$value.'"><img src="'.__ROOT__.'/Public/img/downpic.gif" style="padding:0 3px;"></a>';
        }
    }
    return $file_link;
}

//根据ID号获取机构名称
function getAgencynameById($str){
    $id = (int)$str;
    $map['id'] = $id;
    $name = M('Department')->where($map)->getField('name');
    return $name;
}

//根据用户UID返回用户名
function getUsernameByUid($uid){
    $map['id'] = $uid;
    return M('User')->where($map)->getField('username');
}

/**
 * 获取机构用户名称
 * @param $uid
 * @return mixed
 */
function getUserTrueNameById($uid){
    $map['id'] = $uid;
    return M('User')->where($map)->getField('name');
}

/**
 * 根据机构id获取机构下的所有人员
 * @param $department
 * @return mixed
 */
function getUserNameByDepartment($department){
    $map['department'] = $department;
    $map['typeid']     = array('neq',0);
    return M('User')->where($map)->select();
}
//根据查新员ID返回查新员联系方式
function getTelByAgencyid($id){
    $map['agencyid'] = $id;
    return M('User')->where($map)->getField('tel');
}

//获取所有机构
function getAllDepart(){
    return M('Department')->select();
}

//根据id得到学科名称
function getSchMore($id){
    $info = M('SchoolMore')->find($id);
    return $info['title'];
}
//根据机构类型id获取机构类型汉字
function getTitleById($id){
    $array = getTypeSelect();
    foreach($array as $key=>$value){
        if($key ==$id){
            return $value;
        }
    }
}

//根据科技查新ID获取委托人
function getWtrnameByKjcxId($id){
    return M('kjcx')->where("id=$id")->getField('wtrname');
}

//把数组转变为字符串
function arr2str($arr,$tag=','){
    return implode($tag, $arr);
}

//根据角色ID获取角色名称
function getRoleById($id){
    $map['id'] = $id;
    return M('Auth_group')->where($map)->getField(title);
}
//根据角色ID获取角色名称
function getUserById($id){
    $map['uid'] = $id;
    $list =  M('Auth_group_access')->join('k_auth_group ON k_auth_group_access.group_id=k_auth_group.id')->where('uid='.$id)->field('title')->find();
    return $list['title'];
}
//根据用户名获取总的基础费
function getTotalCxf($username){
    $map['cx_user_name'] = $username;
    return M('Kjcx')->where($map)->count('cxf');
}

//根据用户名获取总的加急费
function getTotalJjf($username){
    $map['cx_username'] = $username;
    return M('Kjcx')->where($map)->count('jjf');
}
//根据用会获取总费用
function getTotalMoney($username){
    return true;
}

//根据用户名id获取参与查新任务数目
function getTotalCxTask($id){
    $map['cx_user_name'] = $id;
    return M('Kjcx')->where($map)->count();
}

//根据用户id获取参与查新任务数目
function getTotalShTask($id){
    $map['sh_user_name'] = $id;
    return M('Kjcx')->where($map)->count();
}

//根据用户ID获取的退单的数目
function getTotalTdTask($id){
    $map['user_bh'] = $id;
    $map['process_id'] = -1; //-1,15
    return M('LogKjcx')->where($map)->count();
}

//生成系统auth_key
function build_auth_key()
{
    $chars = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $chars = str_shuffle($chars);
    return substr($chars, 0, 40);
}

//获取订单所有状况
function getTaskStatus(){
    $status = array(
        '0'=>'全部订单',
        '1'=>'未完成订单',
        '2'=>'已经完成订单',
        '3'=>'退单'
    );
    return $status;
}

//获取机构人员角色
function getInstitutionRoleGroup(){
    $map['module'] = 'Institution';
    return M('AuthGroup')->where($map)->select();
}

/**
 * @param $id   传入的组id
 * @return mixed|string  组名
 */
function getAuthName($id){
    $id     = intval($id)?intval($id):0;
    $res    = M('AuthGroup')->where('id='.$id)->getField('title');
    if($res)
    {
        return $res;
    }
    else
    {
        return '用户组不存在';
    }
}
//获取城市名称
function getCityName($area_id){
    $map['area_id'] = $area_id;
    return M('Area')->where($map)->getField('title');
}


//行为日志
function action_log($action = null, $model = null, $record_id = null, $user_id = null,$content=null){
    //参数检查
    if(empty($action) || empty($model) || empty($record_id)){
        return '参数不能为空';
    }
    if(empty($user_id)){
        $user_id = is_login();
    }
    //查询行为,判断是否执行
    $action_info = M('Action')->getByName($action);
    if($action_info['status'] != 1){
        return '该行为被禁用或删除';
    }
    //插入行为日志
    $data['action_id']      =   $action_info['id'];
    $data['user_id']        =   $user_id;
    $data['action_ip']      =   ip2long(get_client_ip());
    $data['model']          =   $model;
    $data['record_id']      =   $record_id;
    $data['create_time']    =   NOW_TIME;
    $data['content']        =   $content;
    //解析日志规则,生成日志备注
    if(!empty($action_info['log'])){
        if(preg_match_all('/\[(\S+?)\]/', $action_info['log'], $match)){
            $log['user']    =   $user_id;
            $log['record']  =   $record_id;
            $log['model']   =   $model;
            $log['time']    =   NOW_TIME;
            $log['data']    =   array('user'=>$user_id,'model'=>$model,'record'=>$record_id,'time'=>NOW_TIME);
            foreach ($match[1] as $value){
                $param = explode('|', $value);
                if(isset($param[1])){
                    $replace[] = call_user_func($param[1],$log[$param[0]]);
                }else{
                    $replace[] = $log[$param[0]];
                }
            }
            $data['remark'] =   str_replace($match[0], $replace, $action_info['log']);
        }else{
            $data['remark'] =   $action_info['log'];
        }
    }else{
        //未定义日志规则，记录操作url
        $data['remark']     =   '操作url：'.$_SERVER['REQUEST_URI'];
    }

     $id =M('ActionLog')->add($data);

    if(!empty($action_info['rule'])){
        //解析行为
        $rules = parse_action($action, $user_id);

        //执行行为
        $res = execute_action($rules, $action_info['id'], $user_id);
    }
    return $id;
}

/**
 * 解析行为规则
 * 规则定义  table:$table|field:$field|condition:$condition|rule:$rule[|cycle:$cycle|max:$max][;......]
 * 规则字段解释：table->要操作的数据表，不需要加表前缀；
 *              field->要操作的字段；
 *              condition->操作的条件，目前支持字符串，默认变量{$self}为执行行为的用户
 *              rule->对字段进行的具体操作，目前支持四则混合运算，如：1+score*2/2-3
 *              cycle->执行周期，单位（小时），表示$cycle小时内最多执行$max次
 *              max->单个周期内的最大执行次数（$cycle和$max必须同时定义，否则无效）
 * 单个行为后可加 ； 连接其他规则
 * @param string $action 行为id或者name
 * @param int $self 替换规则里的变量为执行用户的id
 * @return boolean|array: false解析出错 ， 成功返回规则数组
 */
function parse_action($action = null, $self){
    if(empty($action)){
        return false;
    }

    //参数支持id或者name
    if(is_numeric($action)){
        $map = array('id'=>$action);
    }else{
        $map = array('name'=>$action);
    }

    //查询行为信息
    $info = M('Action')->where($map)->find();
    if(!$info || $info['status'] != 1){
        return false;
    }

    //解析规则:table:$table|field:$field|condition:$condition|rule:$rule[|cycle:$cycle|max:$max][;......]
    $rules = $info['rule'];
    $rules = str_replace('{$self}', $self, $rules);
    $rules = explode(';', $rules);
    $return = array();
    foreach ($rules as $key=>&$rule){
        $rule = explode('|', $rule);
        foreach ($rule as $k=>$fields){
            $field = empty($fields) ? array() : explode(':', $fields);
            if(!empty($field)){
                $return[$key][$field[0]] = $field[1];
            }
        }
        //cycle(检查周期)和max(周期内最大执行次数)必须同时存在，否则去掉这两个条件
        if(!array_key_exists('cycle', $return[$key]) || !array_key_exists('max', $return[$key])){
            unset($return[$key]['cycle'],$return[$key]['max']);
        }
    }

    return $return;
}

/**
 * 执行行为
 * @param array $rules 解析后的规则数组
 * @param int $action_id 行为id
 * @param array $user_id 执行的用户id
 * @return boolean false 失败 ， true 成功
 */
function execute_action($rules = false, $action_id = null, $user_id = null){
    if(!$rules || empty($action_id) || empty($user_id)){
        return false;
    }

    $return = true;
    foreach ($rules as $rule){

        //检查执行周期
        $map = array('action_id'=>$action_id, 'user_id'=>$user_id);
        $map['create_time'] = array('gt', NOW_TIME - intval($rule['cycle']) * 3600);
        $exec_count = M('ActionLog')->where($map)->count();
        if($exec_count > $rule['max']){
            continue;
        }

        //执行数据库操作
        $Model = M(ucfirst($rule['table']));
        $field = $rule['field'];
        $res = $Model->where($rule['condition'])->setField($field, array('exp', $rule['rule']));

        if(!$res){
            $return = false;
        }
    }
    return $return;
}

function get_action_type($type, $all = false){
    $list = array(
        1=>'系统',
        2=>'用户',
    );
    if($all){
        return $list;
    }
    return $list[$type];
}

function show_status_op($status) {
    switch ($status){
        case 0  : return    '启用';     break;
        case 1  : return    '禁用';     break;
        case 2  : return    '审核';       break;
        default : return    false;      break;
    }
}

function get_action($id = null, $field = null){
    if(empty($id) && !is_numeric($id)){
        return false;
    }
    $list = S('action_list');
    if(empty($list[$id])){
        $map = array('status'=>array('gt', -1), 'id'=>$id);
        $list[$id] = M('Action')->where($map)->field(true)->find();
    }
    return empty($field) ? $list[$id] : $list[$id][$field];
}

//格式化时间
function time_format($time = NULL,$format='Y-m-d H:i'){
    $time = $time === NULL ? NOW_TIME : intval($time);
    return date($format, $time);
}

//根据kjcx_id获取报告名称
function getTitleByKjcxId($id){
    $where['id'] = $id;
    return M('Kjcx')->where($where)->getField('xmmc');
}

//根据process_id获取状态名称
function getTitleByProcessId($id,$dep_id=''){
    if($id=='-2'){
        return "委托中";
    }elseif($id=='-4'){
        return '待处理申请';
    }else{
        $map['process_id'] = $id;
        if($dep_id != ''){
            $map['department_id'] = $dep_id;
        }
        return M('CxProcess')->where($map)->getField('title');
    }
}

//获取日志行为名称
function getActionTitle($id){
    $map['id'] = $id;
    return M('Action')->where($map)->getField('title');
}

function subtext($text, $length)
{
    if(mb_strlen($text, 'utf8') > $length)
        return mb_substr($text, 0, $length, 'utf8').'...';
    return $text;
}

/**
 * 计算报告剩余领取时间
 * @param array $list
 * @return array
 */
function getRestTime($list=array()){
    $new_time = strtotime(date('Y-m-d',time()));
    if(!empty($list)){
        foreach($list as $k=>$v){
            if($v['lqrq']){
                $d = strtotime($v['lqrq'])-$new_time;
                if($d>0){
                    $list[$k]['date'] = date('d',$d);
                }elseif(0==$d){
                    $list[$k]['date'] = 1;
                }else{
                    $list[$k]['date'] = 0;
                }
            }else{
                $list[$k]['date'] = 0;
            }
        }
    }
    return $list;
}
//数组去重，去空
function checkarr2($arr){
    $arr1=array();
    foreach($arr as $k=>$v){
        $v=trim($v);
        if($v==''){continue;}
        if(in_array($v,$arr1)){continue;}
        $arr1[]=$v;
    }
    //sort($arr1);
    return $arr1;
}
//根据id得到临时文件路径
function getUrlDir($id){
    $id = intval($id);
    $list = M('Attachment')->where('id='.$id)->field('dir,title_r')->find();
    return $list['dir'].$list['title_r'];
}

/**
 * @param $msg   错误提示语
 * 用于js本页面提示
 */
function JsLocation ($msg)
{
   echo  "<script>
            var msg = '$msg';
            alert(msg);
            window.history.go(-1);
        </script>";


}

/**
 * 定义江苏省下的城市名称
 * @param string $id
 * @return array
 */
function jiangSu($id = '')
{
    $arr = array('南京','苏州', '无锡','常州','南通','泰州', '扬州','盐城','镇江','盐城','宿迁','淮安','徐州','连云港');
    if($id || $id=='0')
    {
       return $arr[$id];
    }
    else
    {
        return $arr;
    }
}
/**
 * 系统加密方法
 * @param string $data 要加密的字符串
 * @param string $key  加密密钥
 * @param int $expire  过期时间 单位 秒
 * return string
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function think_encrypt($data, $key = '', $expire = 0) {
    $key  = md5(empty($key) ? C('DATA_AUTH_KEY') : $key);
    $data = base64_encode($data);
    $x    = 0;
    $len  = strlen($data);
    $l    = strlen($key);
    $char = '';
    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }
    $str = sprintf('%010d', $expire ? $expire + time():0);
    for ($i = 0; $i < $len; $i++) {
        $str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1)))%256);
    }
    return str_replace(array('+','/','='),array('-','_',''),base64_encode($str));
}
/**
 * 系统解密方法
 * @param  string $data 要解密的字符串 （必须是think_encrypt方法加密的字符串）
 * @param  string $key  加密密钥
 * return string
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function think_decrypt($data, $key = ''){
    $key    = md5(empty($key) ? C('DATA_AUTH_KEY') : $key);
    $data   = str_replace(array('-','_'),array('+','/'),$data);
    $mod4   = strlen($data) % 4;
    if ($mod4) {
        $data .= substr('====', $mod4);
    }
    $data   = base64_decode($data);
    $expire = substr($data,0,10);
    $data   = substr($data,10);
    if($expire > 0 && $expire < time()) {
        return '';
    }
    $x      = 0;
    $len    = strlen($data);
    $l      = strlen($key);
    $char   = $str = '';
    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }
    for ($i = 0; $i < $len; $i++) {
        if (ord(substr($data, $i, 1))<ord(substr($char, $i, 1))) {
            $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
        }else{
            $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
        }
    }
    return base64_decode($str);
}
/**
 *生成目录
 **/
function makepath($path){
    //这个\没考虑
    $path=str_replace("\\","/",$path);
    $ROOT_PATH=str_replace("\\","/",__ROOT__);
    $detail=explode("/",$path);
    $newpath="";
    foreach($detail AS $key=>$value){
        if($value==''&&$key!=0){
            //continue;
        }
        $newpath.="$value/";
        if((eregi("^\/",$newpath)||eregi(":",$newpath))&&!strstr($newpath,$ROOT_PATH)){continue;}
        if( !is_dir($newpath) ){
            if(substr($newpath,-1)=='\\'||substr($newpath,-1)=='/')
            {
                $_newpath=substr($newpath,0,-1);
            }
            else
            {
                $_newpath=$newpath;
            }
            if(!is_dir($_newpath)&&!mkdir($_newpath)&&ereg("^\/",__ROOT__)){
                return 'false';
            }
            @chmod($newpath,0777);
        }
    }
    return $path;
}

/**
 * 对整数进行可逆加密
 * @param $id
 * @return int
 */
function idEncode($id)
{
    $sid = ($id & 0xff000000);
    $sid += ($id & 0x0000ff00) << 8;
    $sid += ($id & 0x00ff0000) >> 8;
    $sid += ($id & 0x0000000f) << 4;
    $sid += ($id & 0x000000f0) >> 4;

    $sid ^= 952348674;

    return $sid;
}

/**
 * 对通过idDecode加密的数字进行还原
 * @param $sid
 * @return bool|int
 */
function idDecode($sid)
{
    $sid = intval($sid);
    $sid ^= 952348674;

    $id = ($sid & 0xff000000);
    $id += ($sid & 0x00ff0000) >> 8;
    $id += ($sid & 0x0000ff00) << 8;
    $id += ($sid & 0x000000f0) >> 4;
    $id += ($sid & 0x0000000f) << 4;

    return $id;
}
